package com.sy.simpleegg.ui.fragment

import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import androidx.lifecycle.lifecycleScope
import com.sy.simpleegg.R
import com.sy.simpleegg.adapter.SpinnerAdapter
import com.sy.simpleegg.base.BaseMvpFragment
import com.sy.simpleegg.databinding.FragmentLogManageBinding
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.mvp.contract.LogManageContract
import com.sy.simpleegg.mvp.presenter.LogManagePresenter
import com.sy.simpleegg.ui.dialog.LoadingDialog

class LogManageFragment :
    BaseMvpFragment<LogManageContract.View, LogManageContract.Presenter, FragmentLogManageBinding>(),
    LogManageContract.View {

    private var dateArr: Array<String>? = null
    private var selectDate = ""

    private var loadingDialog: LoadingDialog? = null

    companion object {
        fun getInstance(): LogManageFragment = LogManageFragment()
    }

    override fun createPresenter(): LogManageContract.Presenter = LogManagePresenter(lifecycleScope)

    override fun attachLayoutRes(): Int = R.layout.fragment_log_manage

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openEventBus = false
        isCountDownBackHome = false
    }

    override fun initView(view: View) {
        super.initView(view)

        mPresenter?.getLogDirs()

        binding.btnUpload.setOnClickListener {
            if (!isFirstClick()){
                return@setOnClickListener
            }
            uploadLog()
        }

//        binding.rlTouch.setTouchListener(object : TouchRelativeLayout.TouchListener {
//            override fun touch() {
//                startCountDown()
//            }
//        })
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentLogManageBinding {
        return FragmentLogManageBinding.inflate(inflater, container, false)
    }

    override fun lazyLoad() {

    }

    override fun onResume() {
        super.onResume()
        logFile("${javaClass.simpleName} onResume")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            logFile("${javaClass.simpleName}隐藏")
        } else {
            logFile("${javaClass.simpleName}显示")
        }
    }

    override fun refreshSpinner(dateArr: Array<String>?) {
        try {
            if (dateArr.isNullOrEmpty()){
                return
            }
            this.dateArr = dateArr
            binding.spDate.adapter = SpinnerAdapter(dateArr)
            binding.spDate.onItemSelectedListener = object : OnItemSelectedListener{
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    logFile("选中日期：${dateArr[position]}")
                    selectDate = dateArr[position]
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {

                }
            }
            binding.spDate.setSelection(0)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("设置日志路径数据到Spinner异常：${e.message}")
        }
    }

    override fun showUploading(result: Int) {
        showUploadDialog(result)
    }


    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    private fun uploadLog(){
        try {
            if (selectDate.isEmpty()){
                showToastMsg("未选择日期")
                return
            }
            mPresenter?.uploadLog(selectDate)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("上传日志异常：${e.message}")
        }
    }

    /**
     * 显示日志上传窗口
     * @param result 上传结果
     */
    private fun showUploadDialog(result: Int){
        try {
            var msg = ""
            var pbShow = false
            when (result){
                0 -> {
                    msg = "日志上传中，请稍等"
                    pbShow = true
                }
                1 -> {
                    msg = "日志上传完成"
                }
                2 -> {
                    msg = "日志上传失败"
                }
            }
            if (loadingDialog == null) {
                loadingDialog = LoadingDialog(requireContext())
                loadingDialog?.setTitle("日志上传")
                loadingDialog?.setYesOnclickListener("确定", object : LoadingDialog.onYesOnclickListener{
                    override fun onYesClick(pbVisable: Boolean) {
                        if (!pbVisable) {
                            loadingDialog?.dismiss()
                            loadingDialog = null
                        }
                    }
                })

                loadingDialog?.setOnShowListener(DialogInterface.OnShowListener {
                    loadingDialog?.window!!
                        .clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
                    loadingDialog?.window!!
                        .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
                })
                loadingDialog?.setOnDismissListener(DialogInterface.OnDismissListener {
                    if (loadingDialog != null) {
                        loadingDialog!!.dismiss()
                        loadingDialog = null
                    }
                })
            }
            loadingDialog?.setMessage(msg)
            loadingDialog?.showProgressBar(pbShow)
            if (!loadingDialog?.isShowing!!) {
                loadingDialog?.show()
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            logFile("上传日志异常：" + e.message)
        }
    }
}